
<!--
	作者：lsd
	时间：2020-4-27
	描述：未确认申请
-->
<template>
	<div class="m-view-purcheaserManager m-window">
		<!-- 搜索头 -->
		<div class="m-condition">
			<el-row :gutter="5">
				<el-form
					:model="formSearch"
					ref="formSearch"
					label-width="70px"
					:inline-message="true"
					label-position="left"
				>
					<el-col :span="5">
						<el-form-item label="任务号" class="rightItem">
							<el-input
								value-key="id"
								v-model.trim="formSearch.taskNo"
								placeholder="请输入"
								clearable
								maxlength="20"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="工厂" class="rightItem">
							<el-input
								value-key="id"
								v-model.trim="formSearch.plantCode"
								placeholder="请输入"
								clearable
								maxlength="20"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item label="采购申请号" class="rightItem">
							<el-input
								value-key="id"
								v-model.trim="formSearch.requestNo"
								placeholder="请输入"
								clearable
								maxlength="20"
							></el-input>
						</el-form-item>
					</el-col>
				</el-form>

				<el-col :span="2">
					<el-button type="primary" @click="search">查询</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="confirm">确认</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="openDia(false)">拒绝</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="openDia(true)">转派</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="printBill('purchaseBill')">打印申请单</el-button>
				</el-col>
			</el-row>
		</div>

		<!-- 表单 -->
		<div class="m-agTable m-bottom" v-loading="loading">
			<ag-grid-component
				ref="agGridComponent"
				:getRowData="rowData"
				:getRowSelection="'multiple'"
				:tableName="'toDoList'"
				:getGridOptions="toDoGridOptions"
				:getColumnDefs="columnDefs"
				:isColFit="true"
				:systemInfo="$systemInfo"
			></ag-grid-component>
		</div>

		<!-- 页脚 -->
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="pageInfo.currentPage"
				:page-sizes="[30,50,100,150,200 ]"
				:page-size="pageInfo.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
			></el-pagination>
		</div>

		<!-- 转派窗口 -->
		<el-dialog
			:title="diaTittle"
			:visible.sync="diaTransfer"
			width="60"
			v-dialogDrag
			:before-close="closeDia"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<el-form
				:model="formTransfer"
				v-loading="loadingDia"
				ref="formTransfer"
				label-width="100px"
				class="demo-ruleForm"
				:rules="rules"
			>
				<el-form-item label="转派给" prop="sapNum" v-if="isTransfer">
					<el-select
						v-model="formTransfer.sapNum"
						filterable
						value-key="sapNum"
						:clearable="false"
						:filter-method="filterSupplier"
						placeholder="请选择采购员"
					>
						<el-option
							v-for="item in optionsPurcheaser"
							:key="item.sapNum"
							:label="item.purcheaserName"
							:value="item"
						>
							<span style="float: left">{{ item.purcheaserName }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.sapNum }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="备注" prop="memo">
					<el-input
						type="textarea"
						v-model="formTransfer.memo"
						:rows="2"
						placeholder="请输入备注"
						maxlength="50"
						show-word-limit
					></el-input>
				</el-form-item>
			</el-form>

			<span slot="footer" class="dialog-footer">
				<el-button @click="closeDia">取消</el-button>
				<!-- 转派 -->
				<el-button type="primary" v-show="isTransfer" @click="transfer" :loading="loadingDia">确定</el-button>
				<!-- 拒绝 -->
				<el-button type="primary" v-show="!isTransfer" @click="refuse" :loading="loadingDia">确定</el-button>
			</span>
		</el-dialog>

		<!-- 历史记录弹窗 -->
		<history-log :formData="historyData" :dialogVisible="diaShow" @dialogClose="diaShow = false"></history-log>
	</div>
</template>
  
<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import gridOptions from "lesso-common/public/gridOptions";
import Vue from "vue";
import historyLog from "./common/dialogSrmHistoryLog";
import { startPrint } from 'lesso-common/webprint'
import fileStream from "@/public/fileStream";
import apienv from '@/api/env';
import constant from "@/public/constant";
import print from "./common/printPc";


const ENV = apienv[constant.appenv]
/**
 * @group toDoList
 * 未确认申请
 */
export default {
	name: 'toDoList',
	components: { historyLog },
	data () {
		return {
			formSearch: {//查询表
				taskNo: '',
				plantCode: '',
				requestNo: '',
			},
			formTransfer: { //转派表&拒绝表
				sapNum: '',
				memo: '',
			},
			isTransfer: true, //是否转派， true 转派，false 非转派
			optionsPurcheaser: [],//采购员下拉框列表
			optionsTempPurcheaser: [],//下拉框工具人
			rowData: [], // 表格数据
			//表格参数
			gridOptions: '',
			columnDefs: [],
			//页脚参数
			pageInfo: {
				pageSize: 30,
				currentPage: 1,
			},
			total: 0,
			//弹窗参数
			diaTransfer: false,//转派窗口&拒绝窗口
			diaTittle: '转派',
			//加载参数
			loading: false,//页面的
			loadingDia: false,//弹框的
			diaShow: false,
			historyData: {},//转派记录表
			rules: {
				sapNum: [{
					required: true,
					trigger: ['blur', 'change'],
					message: "不能为空",
				}],
				memo: [{
					required: true,
					trigger: ['blur', 'change'],
					message: "备注不能为空",
				}]
			}
		}
	},
	beforeMount () {
		this.toDoGridOptions = {
			context: {
				componentParent: this
			},
			defaultColDef: {
				sortable: true
			},
			sideBar: {
        toolPanels:[
            {
                id: "columns",
                labelDefault: "Columns",
                labelKey: "columns",
                iconKey: "columns",
                toolPanel: "agColumnsToolPanel"
            }
				]
			},
			rowSelection: "multiple",
			rowDeselection: false,
			rowMultiSelectWithClick: true,
			enableColResize: true,
			localeText: localeText,
			suppressRowClickSelection: true,
			enableFilter: true, //列过滤器
			enableSorting: true, //列排序
			animateRows: true, //排序动画
		}
		this.columnDefs = [
			{
				headerName: "任务号",
				field: "taskNo",
				checkboxSelection: true,
				headerCheckboxSelection: true,
				width: 130,
			},
			{ headerName: "采购申请", field: "requestNo", width: 100 },
			{ headerName: "采购申请项目", field: "requestMxno", width: 115 },
			{ headerName: "采购订单号", field: "purOrdNo", width: 105 },
			{ headerName: "采购订单项目", field: "purOrdMxNo", width: 115 },
			{ headerName: "物料编码", field: "matCode", width: 95 },
			{ headerName: "物料描述", field: "matName", width: 155 },
			{ headerName: "申请数量", field: "requestAmount", width: 90 },
			{ headerName: "单位", field: "unitCode", width: 65 },
			{ headerName: "申请部门", field: "purGroupName", width: 90 },
			{ headerName: "申请者", field: "requester", width: 78 },
			{ headerName: "申请备注", field: "remark", width: 105 },
			{ headerName: "备注", field: "memo", width: 105 },
			{ headerName: "负责人", field: "handlerName", width: 78 },
			{
				headerName: "转派人",
				field: "transferName",
				width: 78,
				cellRenderer: (params) => {
					if (params.value) {
						return `<span style="position: absolute; right: 1px; bottom: 1px; left: 1px; top: 1px;background: #FFFF00;">
							${params.value}
						</span>`;
					} else {
						return '';
					}
				}
			},
			{ headerName: "工厂", field: "plantName", width: 150 },
			{ headerName: "申请日期", field: "sapCreateDate", width: 90, hide: true },
			{ headerName: "交货日期", field: "modifyDate", width: 90, hide: true },
			{
				headerName: "转派记录",
				width: 120,
				cellRendererFramework: Vue.extend({
					template: `<span>
                                    <el-button 
                                        type="text" 
                                        class="rendererClass" 
                                        size="mini" 
                                        @click="openHistoryDia(params.data)">
                        查看
                        </el-button>
                    </span>`,
					methods: {
                        /**
                         * @vuese
                         * 项目列表的按钮点击事件
                         * 
                         * @arg row:行数据;
                         */
						openHistoryDia (row) {
							this.params.context.componentParent.historyData = row;
							this.params.context.componentParent.diaShow = true;
						},
					}
				})
			}
		];

	},
	mounted () {
		this.search();
	},
	methods: {
		/**
		 * @vuese
		 * 查询方法
		 * 
		 * @arg 参数是布尔值， true就是点击触发，false就是非点击触发
		 */
		search (isClick) {
			this.loading = true;
			this.pageInfo.currentPage = isClick ? 1 : this.pageInfo.currentPage;
			let param = {
				...this.formSearch,
				handler: this.$global.user.idmNum,
				...this.pageInfo,
			};
			_Api
				.getToDoList(param)
				.then(res => {
					this.loading = false;
					if (res.data.code == 1) {
						this.rowData = res.data.rows;
						this.total = res.data.total
						this.$refs.agGridComponent.gridOptions.api.setRowData(this.rowData);
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loading = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese
		 * 确定任务方法
		 */
		confirm () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
			if (row.length <= 0) {
				this.$alert("提示：请至少选择一个任务", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			}
			let list = [];
			for (let i = 0; i < row.length; i++) {
				let { taskNo, taskMxno, requestId, requestNo, requestMxno, handler, handlerName, state, sapFlag, id } = row[i]
				let param = {
					taskNo,
					taskMxno,
					requestId,
					requestNo,
					requestMxno,
					handler,
					handlerName,
					state,
					sapFlag,
					id,
					modifyerId: this.$global.user.id,
					modifyer: this.$global.user.employeeName//修改人
				}
				list.push(param)
			}

			this.$confirm(`是否确认该任务`, "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				this.loading = true;
				_Api
					.confirmTask(list)
					.then(res => {
						this.loading = false;
						if (res.data.code == 1) {
							this.$message({
								message: `确认成功！`,
								type: "success"
							});
							this.search();//刷新
						} else {
							this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
						}
					})
					.catch(err => {
						this.loading = false;
						this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					});
			})
		},

		/**
		 * @vuese
		 * 拒绝任务方法
		 */
		refuse () {
			this.$refs['formTransfer'].validate((valid) => {
				if (valid) {
					this.loadingDia = true;
					let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
					let list = [];
					for (let i = 0; i < row.length; i++) {
						let { requestNo, requestMxno, id } = row[i]
						let param = {
							id,
							requestNo,
							requestMxno,
							...this.formTransfer,
							modifyerId: this.$global.user.id,
							modifyer: this.$global.user.employeeName//修改人
						}
						delete param.sapNum
						list.push(param)
					}
					_Api
						.refuseTask(list)
						.then(res => {
							this.loadingDia = false;
							if (res.data.code == 1) {
								this.$message({ message: "拒绝成功", type: "success" });
								this.search()//刷新数据
								this.closeDia();
							} else {
								this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
							}
						})
						.catch(err => {
							this.loadingDia = false;
							this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
						});
				}
			})
		},

		/**
		 * @vuese
		 * 转派方法
		 */
		transfer () {
			this.$refs['formTransfer'].validate((valid) => {
				if (valid) {
					this.loadingDia = true;
					let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
					let list = [];
					for (let i = 0; i < row.length; i++) {
						let { requestId, requestNo, requestMxno, id, handler, handlerName } = row[i]
						let param = {
							requestId,
							requestNo,
							requestMxno,
							id,
							handler,
							handlerName,
							memo: this.formTransfer.memo,
							chandler: this.formTransfer.sapNum.sapNum,
							chandlerName: this.formTransfer.sapNum.purcheaserName,
							modifyerId: this.$global.user.id,
							modifyer: this.$global.user.employeeName//修改人
						}
						list.push(param)
					}

					_Api
						.transferTask(list)
						.then(res => {
							this.loadingDia = false;
							if (res.data.code == 1) {
								this.$message({ message: "转派成功", type: "success" });
								this.search()//刷新数据
								this.closeDia();
							} else {
								this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
							}
						})
						.catch(err => {
							this.loadingDia = false;
							this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
						});
				}
			});
		},

		/**
		 * @vuese
		 * 打开转派&拒绝窗口方法
		 * 
		 * @arg 
		 * isTransfer这个参数是布尔值，true表示为转派窗口，false表示为拒绝窗口
		 */
		openDia (isTransfer) {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
			if (row.length <= 0) {
				this.$alert("提示：请至少选择一个任务", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			}
			this.isTransfer = isTransfer;
			this.diaTransfer = true;
			this.diaTittle = isTransfer ? '转派' : '拒绝';
			if (isTransfer) {
				//判断是否有其他状态的
				let code = row[0].plantCode;
				if (row.findIndex(e => e.plantCode != code) > -1) {
					this.$alert("选中的任务中有不同工厂的任务，请重新选择！", { showClose: false, confirmButtonText: "确定", customClass: "alertPrompt" });
					return
				}
				this.getPurcheaserList();
				this.formTransfer.sapNum = {
					sapNum: row[0].handler,
					purcheaserName: row[0].handlerName
				}
			}
		},

		/**
		 * @vuese 
		 * 根据工厂信息获取采购员方法
		 */
		getPurcheaserList () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
			this.loadingDia = true;
			_Api
				.getAllPurchaserList({ plantCode: row[0].plantCode })
				.then(res => {
					this.loadingDia = false;
					if (res.data.code == 1) {
						this.optionsPurcheaser = res.data.rows.filter(e => e.sapNum != this.$global.user.sapNum);
						this.optionsTempPurcheaser = res.data.rows.filter(e => e.sapNum != this.$global.user.sapNum);
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loadingDia = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese
		 * 过滤采购员
		 * 
		 * @arg 参数是String，是采购员的sapNum
		 */
		filterSupplier (value) {
			if (value != '') {
				this.optionsPurcheaser = this.optionsTempPurcheaser.filter(item => item.sapNum.indexOf(value) > -1 || item.purcheaserName.indexOf(value) > -1)
			} else {
				this.optionsPurcheaser = this.optionsTempPurcheaser;
			}
		},

		/**
		 * @vuese
		 * 改变页脚总条数方法
		 */
		handleSizeChange (val) {
			this.pageInfo.pageSize = val;
			this.pageInfo.currentPage = 1;
			this.search();
		},

		/**
		 * @vuese
		 * 翻页方法
		 */
		handleCurrentChange (val) {
			this.pageInfo.currentPage = val;
			this.search();
		},

		/**
		 * @vuese
		 * 清空参数方法
		 */
		clearParamter () {
			this.formTransfer = {
				sapNum: '',
				memo: ''
			}
			this.$refs.formTransfer.resetFields();
		},

		/**
		 * @vuese
		 * 关闭弹框方法
		 */
		closeDia () {
			this.diaTransfer = false;
			this.clearParamter();
		},
        /**
         * @vuese
         * 打印采购申请单
         * @arg 参数tempType为打印模板编码
         */
		printBill (tempType) {
			if (constant.userAgent == 'web') {
				fileStream.getFileInfo(tempType).then((data) => {
					startPrint({
						basicUrl: ENV['srm'], //权限接口地址
						reportUrl: `${ENV['srm']}download2?viewPath=${data.url}&groupName=${data.groupName}`, //打印模板地址
						dataUrl: 'mstMyTodoTask/printUnconfirmedRequest', //数据接口地址
						params: {
							...this.formSearch,
							'token': '',
							'handler': this.$global.user.idmNum,
							'state': 0
						}, //参数对象
						printType: 'preview'     // 打印方式print直接打印，preview先预览
					})
				}).catch((err) => {
					this.$alert(err, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					});
				})
			} else {
				let params = {
					...this.formSearch,
					'handler': this.$global.user.idmNum,
					'state': 0
				}
				print.printPc("purchaseBill_pc", params)
			}
		}
	}
}
</script>
  
